<?php
namespace app\api\controller;
use think\Session;
use think\Cookie;
use think\Controller;

class User extends  Controller
{
	//判断是否已登录
	public function check_login()
	{
		if(request()->isGet())
		{
			// 判断指定前缀的Session值是否存在
			if(Session::has('account','think') && Session::get('account','think') == Cookie::get('account','think_'))         
			{
				//判断此用户是否已经投过此类型的票
				$account = Session::get('account','think');
				$status = db('voter',[],false)->where('account',$account)->column('status');

				$info['code'] = 0;
	            $info['message'] = '已登录';
	            $info['data'] = Array('account'=>Session::get('account','think'),'status'=>$status);
	            return json_encode($info,JSON_UNESCAPED_UNICODE);
			}else
			{
				$info['code'] = 0;
	            $info['message'] = '尚未登录';
	            return json_encode($info,JSON_UNESCAPED_UNICODE);
			}
		}else
		{
			$info['code'] = -1;
            $info['message'] = '请求错误';
            return json_encode($info,JSON_UNESCAPED_UNICODE);
		}
	}

	//登录逻辑
	public function login()
	{
		
		if(request()->isPost())
		{
			$post_json = file_get_contents("php://input");
			$data = json_decode($post_json,true);
			
			//强校验
    		$validate = validate('Login');
	        if(!$validate->check($data)) {
	        	$info['code'] = -1;
	            $info['message'] = $validate->getError();
	            return json_encode($info,JSON_UNESCAPED_UNICODE);
	        }
	        //获取数据并校验
	        $res = model('User')->get(['account'=>$data['account']]);
	        if(!$res || $res->password != $data['password'])
	        {
	        	$info['code'] = 0;
	        	$info['message'] = '账号或密码错误';
	        	return json_encode($info,JSON_UNESCAPED_UNICODE);
	        }

			// 赋值think作用域
			Session::set('account',$data['account'],'think');
			//Session::set('password',$data['password'],'think');
			// 设置cookie 前缀为think_
			Cookie::set('account',$data['account'],['prefix'=>'think_','expire'=>86400,'httponly'  => '',]);

	        $info['code'] = 0;
	        $info['message'] = '登录成功';
	        $info['data'] = $data['account'];
	        return json_encode($info,JSON_UNESCAPED_UNICODE);
		}else
		{
			$info['code'] = -1;
        	$info['message'] = '非法方式传输';
        	return json_encode($info,JSON_UNESCAPED_UNICODE);
		}
	}

	//退出
	public function logout()
	{
		Session::clear('think');
		// 删除指定前缀的cookie
		Cookie::delete('account','think_');

		$info['code'] = 0;
        $info['message'] = '退出成功';
        return json_encode($info,JSON_UNESCAPED_UNICODE);
	}
}